from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext.webapp import template

class HelloHandler(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'hello.html')
    self.response.out.write(template.render(path, template_values))

class QuizHandler(webapp.RequestHandler):
  def get(self):
    template_values = {'name' : self.request.get('name') }
    path = os.path.join(os.path.dirname(__file__), 'quiz.html')
    self.response.out.write(template.render(path, template_values))

class GradeQuizHandler(webapp.RequestHandler):
  def get(self):
    addition_guess = self.request.get('addition')
    capital_guess = self.request.get('capital').strip().lower().capitalize()
    template_values = {'name' : self.request.get('name'), 'wrong_answers': []}

    if capital_guess != 'Sacramento':
      template_values['wrong_answers'].append(WrongAnswer('the capital of California', capital_guess, 'Sacramento'))

    elif capital_guess != '':
      template_values['wrong_answers'].append(WrongAnswer('the capital of California', capital_guess, 'Sacramento'))

    if addition_guess != '7':
      template_values['wrong_answers'].append(WrongAnswer('3 + 4', addition_guess, 7))

    path = os.path.join(os.path.dirname(__file__), 'grade_quiz.html')
    self.response.out.write(template.render(path, template_values))

class WrongAnswer:
  def __init__(self, question, guess, correct):
    self.question = question
    self.guess = guess
    self.correct = correct

class ByeHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write('Goodbye app engine world!')

class DiceHandler(webapp.RequestHandler):
  def get(self):
    times = self.request.get('times')
    times.isdigit()
    self.response.out.write('Rolling ' +  str(times) + ' times.</br>')

    import random

    count = 0

    for i in range(int(times)):
      count = count + 1
      dice_1 = random.randint(1, 6)
      dice_2 = random.randint(1, 6)
      self.response.out.write(str(dice_1) + ' ' + str(dice_2) + '</br>')
      if (dice_1 == 1 and dice_2 == 1):
        self.response.out.write("Got snake eyes!<br>")
      if (dice_1 == 6 and dice_2 == 6):
        self.response.out.write("Got double sixes!<br>")

    self.response.out.write("You rolled the dice " + str(times) + " times .")


def main():
  application = webapp.WSGIApplication([('/hello.*', HelloHandler), ('/goodbye.*', ByeHandler), ('/dice.*', DiceHandler), ('/quiz', QuizHandler), ('/grade_quiz', GradeQuizHandler)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
